import Taro, { useLoad } from "@tarojs/taro"
import { useEffect, useRef } from "react"

export const usePageShow = (callback: () => void) => {
  const onShowEventIdRef = useRef<string>()
  useLoad(() => { 
    const onShowEventId = onShowEventIdRef.current = Taro.getCurrentInstance().router?.onShow
    if (onShowEventId) { 
      Taro.eventCenter.off(onShowEventId)
      Taro.eventCenter.on(onShowEventId, callback)
    }
  })
  useEffect(() => { 
    const onShowEventId = onShowEventIdRef.current
    if (onShowEventId) { 
      Taro.eventCenter.off(onShowEventId)
      Taro.eventCenter.on(onShowEventId, callback)
    }
  })
}

export const usePageHide = (callback: () => void) => { 
  const onHideEventIdRef = useRef<string>()
  useLoad(() => { 
    const onHideEventId = onHideEventIdRef.current = Taro.getCurrentInstance().router?.onHide
    if (onHideEventId) { 
      Taro.eventCenter.off(onHideEventId)
      Taro.eventCenter.on(onHideEventId, callback)
    }
  })
  useEffect(() => { 
    const onHideEventId = onHideEventIdRef.current
    if (onHideEventId) { 
      Taro.eventCenter.off(onHideEventId)
      Taro.eventCenter.on(onHideEventId, callback)
    }
  })
}

export const usePageReady = (callback: () => void) => { 
  const onReadyEventIdRef = useRef<string>()
  useLoad(() => { 
    const onReadyEventId = onReadyEventIdRef.current = Taro.getCurrentInstance().router?.onHide
    if (onReadyEventId) { 
      Taro.eventCenter.off(onReadyEventId)
      Taro.eventCenter.on(onReadyEventId, callback)
    }
  })
  useEffect(() => { 
    const onReadyEventId = onReadyEventIdRef.current
    if (onReadyEventId) { 
      Taro.eventCenter.off(onReadyEventId)
      Taro.eventCenter.on(onReadyEventId, callback)
    }
  })
}